﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Road3App.Model.CrossroadNs;
using System.Collections.ObjectModel;
using Road3App.Model.CrossroadNs.TrafficlightNs;

namespace Road3App.ViewModels
{
    public class EditCrossRoadPhasesViewModel : ViewModelBase
    {
        private CrossRoad _cr;

        private CrossroadViewModel _crvm;
        public CrossroadViewModel CrossroadVM
        {
            get { return _crvm; }
            set { _crvm = value; RaisePropertyChanged("CrossroadVM"); }
        }

        public ObservableCollection<Phase> PhaseCollection
        {
            get { return _cr.PhaseCollection; }
            set { _cr.PhaseCollection = value; RaisePropertyChanged("PhaseCollection"); }
        }

        private Phase _selectedPhase;
        public Phase SelectedPhase
        {
            get { return _selectedPhase; }
            set { _selectedPhase = value; RaisePropertyChanged("SelectedPhase"); LoadStates(); }
        }


        public EditCrossRoadPhasesViewModel(CrossRoad cr)
        {
            _cr = cr;
            CrossroadVM = new CrossroadViewModel(_cr, "trafficlight");
        }

        public void LoadStates()
        {
            if (SelectedPhase == null)
                return;

            _cr.Grid.Where(c => c.TrafficLight != null).ToList().ForEach(c => c.TrafficLight.State = SelectedPhase.States[c.Coords]);
        }

        public void SaveStates()
        {
            if (SelectedPhase == null)
            {
                if (PhaseCollection.Count == 0)
                    AddPhase();

                SelectedPhase = PhaseCollection.First();
            }

            _cr.Grid.Where(c => c.TrafficLight != null).ToList().ForEach(c => SelectedPhase.AddState(c.Coords, c.TrafficLight.State));
        }

        public void AddPhase()
        {
            Phase phase = new Phase() { Length = 20 };
            phase.AddStates(TrafficLightStates.Red, _cr.Grid.Where(c => c.TrafficLight != null));
            PhaseCollection.Add(phase);
        }

        public void InsertPhase()
        {
            if (SelectedPhase == null)
            {
                AddPhase();
                return;
            }

            int index = PhaseCollection.IndexOf(SelectedPhase);
            if (index < 0)
            {
                AddPhase();
                return;
            }

            Phase phase = new Phase() { Length = 20 };
            phase.AddStates(TrafficLightStates.Red, _cr.Grid.Where(c => c.TrafficLight != null));
            PhaseCollection.Insert(index + 1, phase);
        }

        public void RemovePhase()
        {
            if (SelectedPhase == null)
                return;

            PhaseCollection.Remove(SelectedPhase);
        }
    }
}
